#!/usr/bin/env python
#
#       archive.py
#
#
#       Copyright (C) 2011 Joe Tannenbaum <jtannen1@binghamton.edu>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#

import os, time, shutil

def load_db_file(config):
    db_file = open(os.path.join(config['PROFILE'], 'db'))
    folder_lists = [[line for line in folder.split('\n') if line.strip()] for folder in db_file.read().split('-') if folder.strip()]
    db = {}
    for folder in folder_lists:
        if len(folder) > 1:
            db[folder[0]] = folder[1:]
        else:
            db[folder[0]] = []
    return db

def write_db_file(db, config):
    folder_lists = [[key]+db[key] for key in db.keys()]
    db_str = '\n-'.join(['\n'.join(folder) for folder in folder_lists])
    f = open(os.path.join(config["PROFILE"], 'db'),'w')
    f.write(db_str)
    f.close()

def write_config_file(config):
    """
    Open config file, examine each line, change data if line is an option
    
    """
    config_file = open('config')
    lines = config_file.read().split('\n')
    config_file.close()
    for i, line in enumerate(lines):
        if not line.startswith('#') and line.strip() and '=' in line:
            k = line.split('=')[0].upper()
            val = '='.join(line.split('=')[1:])
            if k in config.keys():
                lines[i] = '='.join(k,config[k])
    config_file = open('config','w')
    config_file.write('\n'.join(lines))
    config_file.close()

class Archive(object):

    def __init__(self, config):
        self.config = config
        self.db = load_db_file(config)
        self.folders = self.db.keys()

    def edit_config(self, key, val):
        config[key] = val
        write_config_file(config)

    def get_pages(self, folder):
        """
        Returns a list of tuples whose first value is the description of each
        page in the folder and whose second value is the filename of that page.
        
        """
        return [tuple(page.split('`')) for page in self.db[folder]]

    def make_folder(self, foldername):
        if foldername in self.db.keys():
            ret = 1
        else:
            self.db[foldername] = []
            self.folders.append(foldername)
            ret = 0
            os.mkdir(os.path.join(self.config['PROFILE'], foldername))
            write_db_file(self.db, self.config)
        return ret

    def make_page(self, folder, desc, filename):
        self.db[folder].append(desc+'`'+filename)
        write_db_file(self.db, self.config)

    def rename_folder(self, foldername, newname):
        try:
            self.db[newname] = self.db[foldername]
            del self.db[foldername]
            self.folders = self.db.keys()
            os.rename(os.path.join(self.config['PROFILE'], foldername), os.path.join(self.config['PROFILE'], newname))
            ret = 0
        except KeyError:
            ret = 1
        write_db_file(self.db, self.config)
        return ret

    def rename_page(self, folder, idex, newname):
        oldname = self.db[folder][idex].split('`')[0]
        filename = self.db[folder][idex].split('`')[1]
        self.db[folder][idex] = newname+'`'+filename
        write_db_file(self.db, self.config)

    def remove_folder(self, foldername):
        try:
            for i in range(0,len(self.db[foldername])):
                self.remove_page(foldername, i)
            del self.db[foldername]
            self.folders = self.db.keys()
            shutil.rmtree(os.path.join(self.config['PROFILE'], foldername))
            ret = 0
        except KeyError:
            ret = 1
        write_db_file(self.db, self.config)
        return ret

    def remove_page(self, folder, idex):
        page = self.db[folder].pop(idex)
        pagefile = page.split('`')[1]
        pagedir = os.path.join(self.config['PROFILE'], folder, pagefile)
        os.remove(pagedir)
        write_db_file(self.db, self.config)
